# -*- coding: utf-8 -*-
# @Date：2024/7/22 15:46:28
# @Author：CJiaの青姝
# @FileName：custom
# @Editor：PyCharm2024
# @Remark：
from typing import List, Any
from typing_extensions import Self

from data.models import DataColumns
from ninja import Router, Field, File, Query, ModelSchema
from ninja.files import UploadedFile
from ninja.pagination import paginate

from utils.cj_ninja import CjFilters, MyPagination
from utils.cj_crud import create, batch_create, delete, batch_delete, update, condition, single
from utils.cj_export import export_data, deal_chinese_key
from utils.cj_response import SuccessResponse, ErrorResponse

router = Router()


class Filters(CjFilters):
    name: str = Field(None, description="模块名称", alias='name')
    path: str = Field(None, description="路由", alias='path')
    title: str = Field(None, description="字段名", alias='title')
    dataIndex: str = Field(None, description="字段索引", alias='dataIndex')

    class Config:
        title = "字段查询参数"


class TableColumns(CjFilters):
    name: str = Field(None, description="管理名称", alias='name')
    path: str = Field(None, description="路由", alias='path')

    class Config:
        title = "表头查询参数"


class DataColumnsSchemaIn(ModelSchema):

    def model_validate(
            cls,
            obj: Any,
            *,
            strict: bool | None = None,
            from_attributes: bool | None = None,
            context: Any | None = None,
    ) -> Self:
        if obj.name == '' or obj.name is None:
            return "管理名称不能为空", 400
        elif obj.path == '' or obj.path is None:
            return "路由不能为空", 400
        elif obj.title == '' or obj.title is None:
            return "字段名不能为空", 400
        elif obj.dataIndex == '' or obj.dataIndex is None:
            return "字段索引不能为空", 400
        # 返回请求数据
        return obj, 200

    class Config:
        title = '创建字段参数'
        model = DataColumns
        model_exclude = ['id', 'creator', 'modifier', 'create_time', 'update_time']


class DataColumnsSchemaOut(ModelSchema):
    key: int = Field(None, description="唯一标识符", alias='key')

    class Config:
        title = '字段对象实例'
        model = DataColumns
        model_fields = "__all__"


@router.post("/custom", response=DataColumnsSchemaOut, summary="创建数据字段")
def create_custom(request, data: DataColumnsSchemaIn):
    """ 创建数据字段 """
    message, code = data.model_validate(data)
    if code == 400:
        return ErrorResponse(msg=message)
    # 调用新增方法
    result = create(request, DataColumns, message)
    # 返回结果
    return SuccessResponse(data=result, msg="新增成功")


@router.post("/custom/export", summary="导入数据字段")
def export_custom(request, file: UploadedFile = File(...)):
    """ 导入数据字段 """
    # 字段关系
    field_relations = {
        "管理名称": "name",
        "路由": "path",
        "字段名": "title",
        "字段索引": "dataIndex",
        "字段是否显示": "show",
        "字段布局": "align",
        "字段宽度": "width",
        "是否为公共字段": "common",
    }
    # 检查字段
    check_list = ["管理名称", "路由", "字段名", "字段索引"]
    # 调用公共导入方法
    export_result = export_data(request, file, check_list)
    # 处理一下数据
    for item in export_result['success']:
        item['字段是否显示'] = True if item['字段是否显示'] == '是' else False
        item['是否为公共字段'] = True if item['字段是否显示'] == '是' else False
    # 处理中文key
    result = deal_chinese_key(export_result, field_relations)
    # 调用批量新增方法
    result_list = batch_create(request, DataColumns, result['success'])
    DataColumns.objects.bulk_create(result_list)
    message = f"成功导入{len(result_list)}条数据，失败信息{result['error']}"
    # 返回结果
    return SuccessResponse(data=result['success'], msg=message)


@router.delete("/custom/{custom_id}", response=DataColumnsSchemaOut, summary="删除数据字段")
def delete_custom(request, custom_id: int):
    """ 删除数据字段 """
    # 调用删除方法
    result, code = delete(DataColumns, custom_id)
    if code != 200:
        return ErrorResponse(code=code, msg=result)
    # 返回结果
    return SuccessResponse(data=result, msg="删除成功")


@router.delete("/custom/batch/del", summary="批量删除数据字段")
def batch_delete_custom(request, ids: List[int]):
    """ 批量删除数据字段 """
    # 调用批量删除方法
    result = batch_delete(request, DataColumns, ids)
    # 返回结果
    return SuccessResponse(data=result, msg="批量删除成功")


@router.put("/custom/{custom_id}", response=DataColumnsSchemaOut, summary="更新数据字段")
def update_custom(request, custom_id: int, data: DataColumnsSchemaIn):
    """ 更新数据字段 """
    message, code = data.model_validate(data)
    if code == 400:
        return ErrorResponse(msg=message)
    # 调用修改方法
    result = update(request, DataColumns, message, custom_id)
    # 返回结果
    return SuccessResponse(data=result, msg="更新成功")


@router.get("/custom", response=List[DataColumnsSchemaOut], summary="获取分页数据字段列表")
@paginate(MyPagination)
def list_custom(request, filters: Filters = Query(...)):
    """获取分页数据字段列表"""
    # 调用分页方法
    result = condition(request, DataColumns, filters)
    # 返回结果
    return result


@router.get("/custom/table/meter", response=List[DataColumnsSchemaOut], summary="获取数据字段表格列")
def list_table_custom(request, filters: TableColumns = Query(...)):
    """获取数据字段表格列"""
    # 数据字段表格列
    result = DataColumns.objects.filter(name__in=[filters.name, "公共字段"], path__in=[filters.path, "/all"])
    # 返回结果
    return result


@router.get("/custom/{custom_id}", response=DataColumnsSchemaOut, summary="获取数据字段")
def get_custom(request, custom_id: int):
    """ 获取数据字段 """
    # 调用根据id获取指定对象方法
    result = single(request, DataColumns, id=custom_id)
    # 返回结果
    return SuccessResponse(data=result)
